package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    //创建驱动对象
    public static WebDriver createDriver(){
        if(driver ==null){
            WebDriverManager.chromedriver().setup();

            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");

            driver = new ChromeDriver(options);

            //设置等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
    //截图
    public void getScreenShot(String str) throws IOException {

        //年月日格式
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        //时分秒毫秒格式，不精确道毫秒容易被覆盖因为执行速度太快了
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        //文件夹时间
        String dirTime = sim1.format(System.currentTimeMillis());
        //文件时间
        String fileTime = sim2.format(System.currentTimeMillis());


        //进行拼接 ./src/test/image/2024-8-30/test01-2052.png(test01就是传的str)
        String filename = "./src/test/image"+"/"+ dirTime +"/" + str + "-" + fileTime+ ".png";
        System.out.println("filename" + filename);

        //屏幕截图
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        //将截图放到指定位置
        FileUtils.copyFile(srcFile,new File(filename));
    }


    public Utils(String url){
        //调用driver对象
        createDriver();
        //访问URL
        driver.get(url);
    }
}
